package com.naihe.anderson.sms.service;

import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.SignatureMsg;
import com.naihe.anderson.sms.manager.SignatureMsgMgr;
import com.naihe.anderson.sms.util.FileUtil;

public class NhSmsMainService extends Service {

	NhSmsApp nhSmsApp;
	SignatureMsgMgr signatureMsgMgr;
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		FileUtil.addLog("NhSmsMainService::onCreate()", NhSmsMainService.class, "NhSmsMainService", null);
		nhSmsApp = (NhSmsApp) getApplication();
		signatureMsgMgr = nhSmsApp.getSignatureMsgMgr();
		initPendingIntent();
	}
	
	private void initPendingIntent(){
		List<SignatureMsg> signatureMsgs = new ArrayList<SignatureMsg>();
		signatureMsgs.addAll(signatureMsgMgr.getSignatureMsgInfo());
		for(SignatureMsg msg : signatureMsgs){
			if(msg.getSignatureMsgStatut() == SignatureMsg.SIGNATUREMSG_STATUT_COMPLETE){
				long currentTime = System.currentTimeMillis();
				if(currentTime < msg.getSignatureMsgTime()){
					signatureMsgMgr.setAlarmManager(msg.getSignatureMsgId(), msg.getSignatureMsgTime());
				} else if(currentTime == msg.getSignatureMsgTime()){
					nhSmsApp.getNhSmsMgr().sendSmsBySignatureMsg(msg);
					msg.setSignatureMsgStatut(SignatureMsg.SIGNATUREMSG_STATUT_SEND);
					signatureMsgMgr.updateSignatureMsgInfo(msg, false);
				} else {
					msg.setSignatureMsgStatut(SignatureMsg.SIGNATUREMSG_STATUT_FAILED);
					signatureMsgMgr.updateSignatureMsgInfo(msg, false);
				}
			}
		}
	}
	
	@Override
	public void onDestroy() {
		FileUtil.addLog("NhSmsMainService::onDestroy()", NhSmsMainService.class, "NhSmsMainService", null);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}
